﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Collections;
using Microsoft.Office.Core;
using Excel = Microsoft.Office.Interop.Excel;

namespace ExtractFiles
{
    static class FileHelper
    {
        public static void WriteToFile(string filePath, ArrayList lines)
        {
            try
            {
                StreamWriter sw = new StreamWriter(filePath);
                foreach (string result in lines)
                {
                    sw.WriteLine(result);
                }
                sw.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static string processFilePath(string parentDirectory, string origFilePath)
        {
            int parentDirLength = parentDirectory.Split('\\').Length;
            string[] splitted = origFilePath.Split('\\');
            string fileName = splitted[parentDirLength - 1];
            for (int i = parentDirLength; i < splitted.Length; i++)
            {
                fileName = fileName + "\\" + splitted[i];
            }
            return fileName;
        }

        public static void CopyToFile(Array destFilePaths, string origDirectory, string destinationDirectoryPath)
        {
            try
            {
                int filecount = 0;
                foreach (string destFile in destFilePaths)
                {
                    string destFilePath = processFilePath(origDirectory, Directory.GetParent(destFile).FullName);
                    string destParentPath = destinationDirectoryPath + "\\" + destFilePath;
                    Directory.CreateDirectory(destParentPath);
                    string[] destFileSplitted = destFile.Split('\\');
                    File.Copy(destFile, destParentPath + "\\" + destFileSplitted[destFileSplitted.Length - 1]);
                    filecount++;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static string[] ReadFromFile(string filePath)
        {
            try
            {
                string[] lines = File.ReadAllLines(filePath);
                return lines;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static string[] MergeToFile(string dirToMerge, string mergedFileDest, string[] filters, string lineBreakStyle, bool isBackupTrue)
        {
            ArrayList results = new ArrayList();
            foreach (string filter in filters)
            {
                string[] result = MergeToFile(dirToMerge, mergedFileDest, filter.Trim(), lineBreakStyle, isBackupTrue);
                foreach (string res in result)
                {
                    results.Add(res);
                }
            }
            string[] resultArray = new string[results.Count];
            for (int i = 0; i < results.Count; i++)
            {
                resultArray[i] = (string) results[i];
            }
            return resultArray;
        }

        public static string[] MergeToFile(string dirToMerge, string mergedFileDest, string filter, string lineBreakStyle, bool isBackupTrue)
        {
            try
            {
                if (isBackupTrue)
                {
                    backupFile(mergedFileDest);
                }
                string[] files = Directory.GetFiles(dirToMerge, filter, SearchOption.AllDirectories);
                StreamWriter sw = new StreamWriter(mergedFileDest);
                foreach (string file in files)
                {
                    string[] splitted = file.Split('\\');
                    string filename = "";
                    for (int i = 5; i < splitted.Length; i++)
                    {
                        filename += (splitted[i] + "\\");
                    }
                    switch (lineBreakStyle)
                    {
                        case "emptyLine":
                            sw.WriteLine("");
                            break;
                        case "fileName":
                            sw.WriteLine("---------------------------------------------------------------------");
                            sw.WriteLine("--" + filename + "--");
                            sw.WriteLine("---------------------------------------------------------------------");
                            break;
                        default:
                            sw.WriteLine("");
                            break;
                    }
                    string[] lines = File.ReadAllLines(file);
                    foreach (string line in lines)
                    {
                        sw.WriteLine(line);
                    }
                    sw.WriteLine("");
                    sw.WriteLine("");
                }
                sw.Close();
                return files;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private static void backupFile(string mergedFileDest)
        {
            string[] dirs = mergedFileDest.Split('\\');
            string[] fn = dirs[dirs.Length - 1].Split('.');
            string parentDir = Directory.GetParent(mergedFileDest).FullName;
            string backupName = parentDir + "\\" + fn[0] + "_backup." + fn[1];
            File.Copy(mergedFileDest, backupName, true);
        }

        public static void WriteToExcelUnique(string outputPath, string[] list)
        {
            object misValue = System.Reflection.Missing.Value;
            Excel.Application excelApp = new Excel.Application();
            Excel.Workbook wb = excelApp.Workbooks.Add(misValue);
            Excel.Worksheet ws = (Excel.Worksheet)wb.ActiveSheet;
            Excel.Range range = ws.get_Range("A1:B" + list.Length);
            for (int i = 1; i <= list.Length; i++)
            {
                if (list[i - 1] != null)
                {
                    string[] item = list[i - 1].Split('/');
                    ((Excel.Range)range[i, 1]).Value = item[0];
                    ((Excel.Range)range[i, 2]).Value = item[1];
                }
                else
                {
                    break;
                }
            }
            wb.SaveAs(outputPath, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
            wb.Close(true, misValue, misValue);
            excelApp.Quit();
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(ws);
                ws = null;
                System.Runtime.InteropServices.Marshal.ReleaseComObject(wb);
                wb = null;
                System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
                excelApp = null;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                GC.Collect();
            }
        }

        public static void WriteToTextUnique(string outputPath, string[] list)
        {
            try
            {
                StreamWriter sw = new StreamWriter(outputPath);
                for (int i = 0; i < list.Length; i++)
                {
                    if (list[i] != null)
                    {
                        sw.WriteLine(list[i]);
                    }
                    else
                    {
                        break;
                    }
                }
                sw.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static void WriteToExcel(string outputPath, string[] fileNames, string[] list)
        {
            object misValue = System.Reflection.Missing.Value;
            Excel.Application excelApp = new Excel.Application();
            Excel.Workbook wb = excelApp.Workbooks.Add(misValue);
            Excel.Worksheet ws = (Excel.Worksheet)wb.ActiveSheet;
            Excel.Range range = ws.get_Range("A1:B" + list.Length);
            for (int i = 1; i <= list.Length; i++)
            {
                ((Excel.Range)range[i, 1]).Value = fileNames[i - 1];
                ((Excel.Range)range[i, 2]).Value = list[i - 1];
            }
            wb.SaveAs(outputPath, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
            wb.Close(true, misValue, misValue);
            excelApp.Quit();
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(ws);
                ws = null;
                System.Runtime.InteropServices.Marshal.ReleaseComObject(wb);
                wb = null;
                System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
                excelApp = null;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                GC.Collect();
            }
        }

        public static void WriteToText(string outputPath, string[] fileNames, string[] list)
        {
            try
            {
                StreamWriter sw = new StreamWriter(outputPath);
                for (int i = 0; i < list.Length; i++)
                {
                    if (fileNames[i] != null)
                    {
                        sw.WriteLine(fileNames[i] + "/" + list[i]);
                    }
                    else
                    {
                        break;
                    }
                }
                sw.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
